package com.wlyuan.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.wlyuan.gateway.config.SecurityProperties;
import com.wlyuan.gateway.utils.ClaimUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * @author yuanjie
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class SecurityGlobalFilter implements GlobalFilter, Ordered {
    private final TokenStore tokenStore;
    private final SecurityProperties securityProperties;
    private final AntPathMatcher excludePathMatcher = new AntPathMatcher();

    private boolean isIgnoreUrl(String requestPath) {
        var excludePatterns = securityProperties.getExcludePatterns();
        return excludePatterns.stream()
                .anyMatch(pattern -> excludePathMatcher.match(pattern, requestPath));
    }

    private String readClaims(String authorization) {
        String token = authorization.replace("Bearer ", "");
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
        Map<String, Object> claims = accessToken.getAdditionalInformation();
        if ( logger.isDebugEnabled()) {
            logger.debug("Claims : {}", claims);
        }
        return JSON.toJSONString(ClaimUtils.convert(claims));
    }

    private Boolean isBearerToken(String authorization) {
        if (StringUtils.isEmpty(authorization)) {
            return false;
        }

        return authorization.startsWith("Bearer");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String authorization = request.getHeaders()
                .getFirst("Authorization");
        if (null == authorization
                || !isBearerToken(authorization)
                || isIgnoreUrl(request.getURI().getPath())) {
            return chain.filter(exchange);
        }

        String claims = readClaims(authorization);
        logger.info("Read claims: {}={}", claims, authorization);
        ServerHttpRequest tokenRequest = exchange.getRequest()
                .mutate()
                .header("claims", claims)
                .build();

        ServerWebExchange exchangeWithClaims = exchange.mutate()
                .request(tokenRequest)
                .build();

        return chain.filter(exchangeWithClaims);
    }

    @Override
    public int getOrder() {
        return -99999;
    }
}
